package fr.cpe.j2ee.projet.mdb;

import java.util.Date;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.ObjectMessage;

import org.hornetq.api.core.TransportConfiguration;
import org.hornetq.api.jms.HornetQJMSClient;
import org.hornetq.api.jms.JMSFactoryType;
import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory;

import fr.cpe.j2ee.projet.ejb.ConversationSession;
import fr.cpe.j2ee.projet.ejb.EmployeeSession;
import fr.cpe.j2ee.projet.model.Message;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;

@Stateless
@LocalBean
public class ChatClient {
	private ConnectionFactory factory;
	private Queue queue;
	
	@EJB
	EmployeeSession employeeSession;
	
	@EJB
	ConversationSession conversationSession;
	
    public ChatClient() {
    	TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class.getName());
    	factory = (ConnectionFactory) HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF,transportConfiguration);
    	queue = HornetQJMSClient.createQueue("chatQueue");
    }
    
    public void sendMessage(String messageContent, int senderId, int conversationId) {
    	System.out.println("Sending message to the queue");
		
		Connection connection;
		
		try {
		    connection = factory.createConnection();
		    Session session = connection.createSession(false,QueueSession.AUTO_ACKNOWLEDGE);
		    MessageProducer producer = session.createProducer(queue);
		    ObjectMessage objectMessage = session.createObjectMessage();
		    
		    Message message = new Message();
		    message.setMesContent(messageContent);
		    message.setEmployee(employeeSession.getById(senderId));
		    message.setConversation(conversationSession.getById(conversationId));
		    message.setMesSendTime(new Date());
		    
		    objectMessage.setObject(message);
		    
		    producer.send(objectMessage);
		    
		    session.close();
		    connection.close();
		} catch (JMSException e) {
		    e.printStackTrace();
		}
    }
}
